package com.ljpz.cart.controller.api;

import com.ljpz.cart.pojo.Cart;
import com.ljpz.cart.service.CartCookieService;
import com.ljpz.cart.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
 *
 * 对外提供接口服务
 *
 * 根据用户id查询购物车列表
 *
 * 根据产品名称进行查询购物车列表
 *
 * Created by liujunchen on 2017/1/11.
 */
@RequestMapping("api/cart")
@Controller
public class ApiCartController {
    @Autowired
    private CartService cartService ;
    @Autowired
    private CartCookieService cartCookieService   ;
    /**
     * 对外提供结构
     *
     *
     * @return
     */
    @RequestMapping(value = "delete/{userId}",method = RequestMethod.DELETE)
    public  ResponseEntity<Void>deleteCartListByUserId(@RequestParam("itemIds")  String itemIds ,
                                                       @PathVariable("userId") Long   userId
                                                      ){
        String[]   itemIdArray  =   itemIds.split("\\|") ;

        try {
            for (String  itemid : itemIdArray)
            {
                //删除购物车中里面的商品
                this.cartService.delete(Long.valueOf(itemid),userId);
            }
            return  ResponseEntity.status(HttpStatus.NO_CONTENT).build();
         } catch (Exception e) {
                 e.printStackTrace();
        }
        return  ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
    @RequestMapping(value = "{userId}",method = RequestMethod.GET)
    public ResponseEntity<List<Cart>>queryCartListByUserId(@PathVariable("userId") Long userId){
        try {
            List<Cart> carts= this.cartService.queryCartlist(userId);
            if (null==carts||carts.isEmpty()){
                return  ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }
            return  ResponseEntity.ok(carts)  ;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null) ;
    }

}
